import 'package:app/controllers/keyboard_theme_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../services/websocket_service.dart';

// 定义主题数据
class KeyboardTheme {
  final String name;
  final Color primaryColor;
  final Color backgroundColor;
  final Color keyBgColor;
  final Color textColor;

  const KeyboardTheme({
    required this.name,
    required this.primaryColor,
    required this.backgroundColor,
    required this.keyBgColor,
    required this.textColor,
  });
}

// 预定义的主题列表
const List<KeyboardTheme> themes = [
  KeyboardTheme(
    name: 'Green Matrix',
    primaryColor: Colors.green,
    backgroundColor: Colors.black,
    keyBgColor: Color(0xFF1A1A1A),
    textColor: Colors.green,
  ),
  KeyboardTheme(
    name: 'Deep Purple',
    primaryColor: Colors.deepPurple,
    backgroundColor: Color(0xFF1A1A1A),
    keyBgColor: Color(0xFF2D2D2D),
    textColor: Colors.deepPurple,
  ),
  KeyboardTheme(
    name: 'Ocean Blue',
    primaryColor: Colors.blue,
    backgroundColor: Color(0xFF0A192F),
    keyBgColor: Color(0xFF172A45),
    textColor: Colors.lightBlue,
  ),
  KeyboardTheme(
    name: 'Amber Glow',
    primaryColor: Colors.amber,
    backgroundColor: Color(0xFF2C2C2C),
    keyBgColor: Color(0xFF3D3D3D),
    textColor: Colors.amber,
  ),
  KeyboardTheme(
    name: 'Rose Gold',
    primaryColor: Color(0xFFFF7D7D),
    backgroundColor: Color(0xFF2D2D2D),
    keyBgColor: Color(0xFF3D3D3D),
    textColor: Color(0xFFFF7D7D),
  ),
];

class KeyboardPage extends StatelessWidget {
  const KeyboardPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.background,
      body: Column(
        children: [
          // 主题选择器
          Container(
            padding: const EdgeInsets.all(16.0),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: themes.map((theme) => Padding(
                  padding: const EdgeInsets.only(right: 8.0),
                  child: ThemeButton(theme: theme),
                )).toList(),
              ),
            ),
          ),
          // 键盘布局
          const Expanded(
            child: Center(
              child: KeyboardLayout(),
            ),
          ),
        ],
      ),
    );
  }
}

// 主题按钮组件
class ThemeButton extends StatelessWidget {
  final KeyboardTheme theme;

  const ThemeButton({
    super.key,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return GetX<KeyboardThemeController>(
      builder: (controller) => InkWell(
        onTap: () => controller.setTheme(theme),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
          decoration: BoxDecoration(
            color: controller.currentTheme.value == theme 
              ? theme.primaryColor.withOpacity(0.2)
              : Colors.transparent,
            border: Border.all(
              color: theme.primaryColor,
              width: 2,
            ),
            borderRadius: BorderRadius.circular(20),
          ),
          child: Text(
            theme.name,
            style: TextStyle(
              color: theme.primaryColor,
              fontWeight: controller.currentTheme.value == theme 
                ? FontWeight.bold 
                : FontWeight.normal,
            ),
          ),
        ),
      ),
    );
  }
}

class KeyboardLayout extends StatefulWidget {
  const KeyboardLayout({super.key});

  @override
  State<KeyboardLayout> createState() => _KeyboardLayoutState();
}

class _KeyboardLayoutState extends State<KeyboardLayout> {
  final WebSocketService _webSocketService = Get.find<WebSocketService>();
  final KeyboardThemeController _themeController = Get.find<KeyboardThemeController>();
  
  // 基础按键单位宽度
  static const double _baseWidth = 50.0;
  static const double _baseHeight = 50.0;
  static const double _spacing = 4.0;

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final currentTheme = _themeController.currentTheme.value;
      return Container(
        color: currentTheme.backgroundColor,
        child: FittedBox(
          fit: BoxFit.contain,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: _buildFunctionKeys(),
                  ),
                  const SizedBox(height: _spacing * 4),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: _buildNumberRow(),
                  ),
                  const SizedBox(height: _spacing),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: _buildQwertyRow(),
                  ),
                  const SizedBox(height: _spacing),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: _buildAsdfRow(),
                  ),
                  const SizedBox(height: _spacing),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: _buildZxcvRow(),
                  ),
                  const SizedBox(height: _spacing),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: _buildBottomRow(),
                  ),
                ],
              ),
              const SizedBox(width: _spacing * 4),
              Column(children: _buildNumPad()),
            ],
          ),
        ),
      );
    });
  }

  Widget _buildKey(
    String label, {
    double widthUnit = 1,
    double heightUnit = 1,
  }) {
    return Obx(() {
      final theme = _themeController.currentTheme.value;
      final bool isPressed = _webSocketService.lastKeyPress[label] ?? false;
      return Container(
        width: _baseWidth * widthUnit,
        height: _baseHeight * heightUnit,
        margin: const EdgeInsets.all(_spacing / 2),
        decoration: BoxDecoration(
          color: isPressed ? theme.primaryColor : theme.keyBgColor,
          border: Border.all(color: theme.primaryColor, width: 2),
          borderRadius: BorderRadius.circular(5),
        ),
        child: Center(
          child: Text(
            label,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: isPressed ? theme.keyBgColor : theme.primaryColor,
              fontSize: 14,
              fontWeight: FontWeight.normal,
            ),
          ),
        ),
      );
    });
  }

  Widget _buildSpacer([double width = _spacing * 4]) {
    return SizedBox(width: width);
  }

  List<Widget> _buildFunctionKeys() {
    return [
      _buildKey('ESC'),
      _buildSpacer(_spacing * 8),
      _buildKey('F1'),
      _buildKey('F2'),
      _buildKey('F3'),
      _buildKey('F4'),
      _buildSpacer(_spacing * 8),
      _buildKey('F5'),
      _buildKey('F6'),
      _buildKey('F7'),
      _buildKey('F8'),
      _buildSpacer(_spacing * 10),
      _buildKey('F9'),
      _buildKey('F10'),
      _buildKey('F11'),
      _buildKey('F12'),
      _buildSpacer(_spacing * 4),
      _buildKey('PRT\nSC'),
      _buildKey('SCR\nLK'),
      _buildKey('PAUSE'),
    ];
  }

  List<Widget> _buildNumberRow() {
    return [
      _buildKey('`'),
      _buildKey('1'),
      _buildKey('2'),
      _buildKey('3'),
      _buildKey('4'),
      _buildKey('5'),
      _buildKey('6'),
      _buildKey('7'),
      _buildKey('8'),
      _buildKey('9'),
      _buildKey('0'),
      _buildKey('-'),
      _buildKey('='),
      _buildKey('←', widthUnit: 2),
      _buildSpacer(),
      _buildKey('INS'),
      _buildKey('HOME'),
      _buildKey('PGUP'),
    ];
  }

  List<Widget> _buildQwertyRow() {
    return [
      _buildKey('TAB', widthUnit: 1.5),
      _buildKey('Q'),
      _buildKey('W'),
      _buildKey('E'),
      _buildKey('R'),
      _buildKey('T'),
      _buildKey('Y'),
      _buildKey('U'),
      _buildKey('I'),
      _buildKey('O'),
      _buildKey('P'),
      _buildKey('['),
      _buildKey(']'),
      _buildKey('\\', widthUnit: 1.5),
      _buildSpacer(),
      _buildKey('DEL'),
      _buildKey('END'),
      _buildKey('PGDN'),
    ];
  }

  List<Widget> _buildAsdfRow() {
    return [
      _buildKey('CAPS', widthUnit: 1.90),
      _buildKey('A'),
      _buildKey('S'),
      _buildKey('D'),
      _buildKey('F'),
      _buildKey('G'),
      _buildKey('H'),
      _buildKey('J'),
      _buildKey('K'),
      _buildKey('L'),
      _buildKey(';'),
      _buildKey('\''),
      _buildKey('ENTER', widthUnit: 2.2),
      _buildSpacer(),
    ];
  }

  List<Widget> _buildZxcvRow() {
    return [
      _buildKey('SHIFT', widthUnit: 3.0),
      _buildKey('Z'),
      _buildKey('X'),
      _buildKey('C'),
      _buildKey('V'),
      _buildKey('B'),
      _buildKey('N'),
      _buildKey('M'),
      _buildKey(','),
      _buildKey('.'),
      _buildKey('/'),
      _buildKey('SHIFT', widthUnit: 2.2),
      _buildSpacer(_spacing * 16),
      _buildKey('↑'),
    ];
  }

  List<Widget> _buildBottomRow() {
    return [
      _buildKey('CTRL', widthUnit: 1.5),
      _buildKey('WIN', widthUnit: 1.5),
      _buildKey('ALT', widthUnit: 1.5),
      _buildKey('', widthUnit: 6.5), // Space bar
      _buildKey('ALT', widthUnit: 1.5),
      _buildKey('FN', widthUnit: 1.5),
      _buildKey('CTRL', widthUnit: 1.5),
      _buildSpacer(),
      _buildKey('←'),
      _buildKey('↓'),
      _buildKey('→'),
    ];
  }

  List<Widget> _buildNumPad() {
    return [
      const SizedBox(height: _spacing * 4),
      Row(
        children: [
          _buildKey('NUM'),
          _buildKey('/'),
          _buildKey('*'),
          _buildKey('-'),
        ],
      ),
      const SizedBox(height: _spacing * 4),
      Row(
        children: [
          Column(
            children: [
              Row(children: [_buildKey('7'), _buildKey('8'), _buildKey('9')]),
              const SizedBox(height: _spacing * 4),
              Row(children: [_buildKey('4'), _buildKey('5'), _buildKey('6')]),
            ],
          ),
          _buildKey('+', heightUnit: 2.5),
        ],
      ),
      const SizedBox(height: _spacing * 4),
      Row(
        children: [
          Column(
            children: [
              Row(children: [_buildKey('1'), _buildKey('2'), _buildKey('3')]),
              const SizedBox(height: _spacing * 4),
              Row(
                children: [
                  _buildKey('0', widthUnit: 2),
                  _buildKey('.', widthUnit: 1),
                ],
              ),
            ],
          ),
          _buildKey('ENTER', heightUnit: 2.5),
        ],
      ),
    ];
  }
}